﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBAC_Class.Read.API.Application.Command;
using RBAC_Class.Read.API.Dto;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Read.API.Application.Command.Users;
using System;
using System.Threading.Tasks;
using NLog;

namespace RBAC_Class.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<UserController> logger;

        public UserController(IMediator mediator, ILogger<UserController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<UserDto>>> Login(string userName, string password)
        {
            try
            {
                LoginCommand cmd = new LoginCommand
                {
                    UserName = userName,
                    Password = password
                };
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "登录失败 - 用户名: {UserName}", userName);
                throw;
            }
        }
        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<List<UserRoleDto>>>> QueryUser([FromQuery] UserQueryCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询用户失败 - 参数: UserName={UserName}, PageIndex={PageIndex}, PageSize={PageSize}", 
                    cmd.UserName, cmd.PageIndex, cmd.PageSize);
                throw;
            }
        }
    }
}
